<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Basicdata;
use app\admin\model\Farmplanting;
use app\admin\model\Farmbaseland;
use app\admin\model\Manages;
use app\admin\model\Image;
use app\admin\model\Area;
use app\admin\model\Villages;

use think\Request;

class Product extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['style'] = 1;
        $this->defaultWhere = $defaultWhere;
    }

    public function index()
    {
        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request)
    {
        return parent::add($request);
    }

    /**
     * Add Post
     */
    public function addPost(Request $request, $redirect = ''){
        $model = model($this->model);

        //save data
        if ($request->isAjax()) {
            $data = $request->param();
            // Insert data
            $data['id'] = Helper::getUUID();
            $data['createDate'] = time();
            $data['createOper'] = $this->admin->id;
            $data['imgUrl'] = $data['coverImg'];

            $result = $model->save($data);
            if($result !== false) {
                // 单图
                if(isset($data['imgId']) && !empty($data['imgId'])){
                    Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'Product']);
                }
                // 多图
                if(isset($data['imgIds']) && !empty($data['imgIds'])){
                    foreach ((array)$data['imgIds'] as $key => $item) {
                        Image::where('id', $item)->update(['relatedId' => $data['id'], 'relatedTable' => 'Product', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                // 详情图
                if(isset($data['detailImgIds']) && !empty($data['detailImgIds'])){
                    foreach ((array)$data['detailImgIds'] as $detailImgId) {
                        Image::where('id', $detailImgId)->update(['relatedId' => $data['id'], 'relatedTable' => 'Product']);
                    }
                }

                // Query执行后的操作
                $model->_after_insert($data);

                // 写入日志
                $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                if ($redirect) {
                    return $this->success('添加成功！', $redirect);
                } else {
                    return $this->success('添加成功！', 'admin/' . strtolower($this->model) . '/index');
                }
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('');
        }
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        // 生产品种
        $plantingInfo = Farmplanting::where(['id' => $info['plantingId']])->field('varietieId')->find();
        $info['varietieName'] = Basicdata::where('id', $plantingInfo['varietieId'])->value('name');
        // 生产基地
        $info['baselandName'] = Farmbaseland::where('id', $info['baselandId'])->value('name');
        // 生产主体
        $info['manageName'] = Manages::where('id', $info['manageId'])->value('name');

        $areaMdl = new Area();
        $city = Helper::makeOptions(
            $areaMdl,
            ['level' => 1],
            ['id' => 'asc']
        );
        $this->assign('city',$city);

        //$this->assign('area', $this->getArea($info));

        // 图集
        $imagesList = Image::where(['relatedId' => $info->id, 'tag' => 'imglist'])->where('imgUrl', 'neq', $info->imgUrl)->order('sorting ASC')->select();
        $this->assign('imagesList', $imagesList);

        return $this->view->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Edit Post
     */
    public function editPost(Request $request, $redirect = ''){
        $model = model($this->model);

        //save data
        if ($request->isAjax()) {
            $data = $request->param();
            // Update data
            $data['updateDate'] = time();
            $data['updateOper'] = $this->admin->id;
            $data['imgUrl'] = $data['coverImg'];

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            if($result !== false) {
                // 单图
                if (isset($data['imgId']) && !empty($data['imgId'])) {
                    Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'Product']);
                }
                // 多图
                if (isset($data['imgIds']) && !empty($data['imgIds'])) {
                    foreach ((array)$data['imgIds'] as $key => $item) {
                        Image::where('id', $item)->update(['relatedId' => $data['id'], 'relatedTable' => 'Product', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                // 详情图
                if (isset($data['detailImgIds']) && !empty($data['detailImgIds'])) {
                    foreach ((array)$data['detailImgIds'] as $detailImgId) {
                        Image::where('id', $detailImgId)->update(['relatedId' => $data['id'], 'relatedTable' => 'Product']);
                    }
                }

                // Query执行后的操作
                $model->_after_update($data);

                // 写入日志
                $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                if ($redirect) {
                    return $this->success('编辑成功！', $redirect);
                } else {
                    return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
                }
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('error !');
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            // 所在地
            $item['area'] = getArea($item);

            // 生产品种
            $plantingInfo = Farmplanting::where(['id' => $item['plantingId']])->field('varietieId')->find();
            $varietie = Basicdata::where('id', $plantingInfo['varietieId'])->field('parentId, name')->find();
            if ($varietie) {
                $crop = Basicdata::where('id', $varietie['parentId'])->field('parentId, name')->find();
                $croptype = Basicdata::where('id', $crop['parentId'])->field('name')->find();
                $item['varietie'] = $croptype['name'] . '-' . $crop['name'] . '-' . $varietie['name'];
            } else {
                $item['varietie'] = '';
            }
            // 生产基地
            if($item['baselandId']){
                $item['baselandId'] = Farmbaseland::where(['id' => $item['baselandId']])->value('name');
            }
            // 生产主体
            if($item['manageId']){
                $item['manageId'] = Manages::where(['id' => $item['manageId']])->value('name');
            }
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }

            if(isset($filter['varietieId']) && $filter['varietieId']){
                $where['varietieId'] = $filter['varietieId'];
            }
            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }

    /**
     * 门店列表
     */
    public function storelist(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Store');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        $where = [

        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        $list = $model->where($where)->limit($start, $length)->select();
        $count = $model->where($where)->count();
        if ($list) {
            foreach ($list as $item) {
                // 所在地
                $item['area'] = getArea($item);
            }
        }

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 产品线下门店列表
     */
    public function saleStoreList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Store');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        if(empty($param['storeIds'])){
            $result = [
                'status' => '0',
                'draw' => $param['draw'],
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
            ];
            return json($result);
        }
        $ids = explode(',', $param['storeIds']);
        $where = [
            'id' => ['in', $ids]
        ];

        $list = $model->where($where)->limit($start, $length)->select();
        $count = $model->where($where)->count();

        if ($list) {
            foreach ($list as $item) {
                // 所在地
                $item['area'] = getArea($item);
            }
        }

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }
}